package com.hbnu.tangyalu.jdbc;

import java.sql.*;

public class JdbcDemo06 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String url = "jdbc:mysql://localhost:3306/class2311?serverTimezone=GMT&useSSL=false&characterEncoding=utf-8";
        String name = "root";
        String pwd = "123456";
        try {
            connection = DriverManager.getConnection(url, name, pwd);
            String sql1="update tb_user set salary=salary - ? where username=?";
            String sql2="update tb_user set salary=salary + ? where username=?";
            preparedStatement=connection.prepareStatement(sql1);
            preparedStatement.setDouble(1,1000);
            preparedStatement.setString(2,"wangwu");
            int count=preparedStatement.executeUpdate();

            preparedStatement=connection.prepareStatement(sql2);
            preparedStatement.setDouble(1,1000);
            preparedStatement.setString(2,"zzx");
            count+=preparedStatement.executeUpdate();
            System.out.println(count==2?"转账成功":"转账失败");
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
        finally {
//            关闭资源从小到大，一个一个的关闭
            try {
                if (resultSet!=null){
                    resultSet.close();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }

            try {
                if (preparedStatement!=null){
                    preparedStatement.close();
                }
            }
            catch (SQLException e){
                e.printStackTrace();
            }

            try {
                if (connection!=null){
                    connection.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
